﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

 
namespace mojoPortal.Web.RS.SBM
{
    public partial class RSManageLocation : RSBasePage
    {
        
        int _companyid = 0;
        int _locationid = 0;
        int _callid = 0;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["callid"] != null)
                _callid = Convert.ToInt32(Request.QueryString["callid"].ToString());
            if (Request.QueryString["locationid"] != null)
                _locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());

            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage();

                RSUserIdentity userIdentity = GetRSUserIdentity();
                _companyid = userIdentity.RSCompanyId;
                if (_companyid > 0)
                {
                    if (Request.QueryString["action"] == "add")
                    {
                        SetRSPageHeader("Add New Location To Service Call");
                        pnlLookupLocation.Visible = true;
                        btnSaveLocation.Enabled = true;
                    }
                    else if (Request.QueryString["action"] == "edit")
                    {
                        SetRSPageHeader("Edit Location");
                        pnlLookupLocation.Visible = false;
                        btnSaveLocation.Enabled = true;
                    }
                    else
                    {
                        SetControlEnabledState(false);
                    }

                    if (_locationid > 0)
                    {
                        txtLocationId.Text = _locationid.ToString();
                        PopulateLocationData(_locationid, _companyid);
                    }
                    if (_callid > 0)
                    {
                        txtCallId.Text = _callid.ToString();
                    }
                }
            }
            if (Request.QueryString["action"] == "add")
            {
                LoadLookupLocation();
            }
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            Response.Redirect(prevurl);
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            
            RSSBMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        protected void gvLookupLocation_SelectedIndexChanged(Object sender, EventArgs e)
        {
            String Locationid = gvLookupLocation.SelectedValue.ToString();
            txtLocationId.Text = Locationid;

            RSUserIdentity userIdentity = GetRSUserIdentity();
            _companyid = userIdentity.RSCompanyId;
            PopulateLocationData(Convert.ToInt32(Locationid), _companyid);
        }

        private void PopulateLocationData(int Locationid, int companyid)
        {
            String strSQL = "select LocationName,Street,City,County,State,Zip,Country,Note,CompanyId,Active from rs_tblLocation where Locationid=@Locationid and companyid=@companyid order by city, state, county";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@Locationid";
            param.Value = Locationid;
            myCommand.Parameters.Add(param);

            param = null;
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            while (myDataReader.Read())
            {
                txtLocationId.Text = Locationid.ToString();
                txtLocationName.Text = myDataReader["LocationName"].ToString();
                txtStreet.Text = myDataReader["Street"].ToString();
                txtCity.Text = myDataReader["City"].ToString();
                txtCounty.Text = myDataReader["County"].ToString();
                txtState.Text = myDataReader["State"].ToString();
                txtZip.Text = myDataReader["Zip"].ToString();
                txtLocationNote.Text = myDataReader["Note"].ToString();
                if(Request.QueryString["action"] == "edit")
                    btnDeleteLocation.Enabled = true;
            }
            myConnection.Close();
        }

        protected void btnClearLocation_Click(object sender, EventArgs e)
        {
            ClearLocationDetail();
        }
        private void ClearLocationDetail()
        {
            txtLocationId.Text = "";
            txtLocationName.Text = "";
            txtStreet.Text = "";
            txtCity.Text = "";
            txtCounty.Text = "";
            txtState.Text = "";
            txtZip.Text = "";
            txtLocationNote.Text = "";
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                _companyid = userIdentity.RSCompanyId;
                if (!String.IsNullOrEmpty(Request.QueryString["locationid"]))
                    _locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());

                if (_companyid > 0 && _locationid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@locationid", SqlDbType.Int, 0, ParameterDirection.Input, _locationid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, _companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblCallLocation WHERE LocationId=@Locationid AND  CompanyId=@companyid; DELETE FROM rs_tblContactLocation WHERE LocationId=@Locationid AND  CompanyId=@companyid; DELETE FROM rs_tblLocation WHERE LocationId=@Locationid AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    ucModalActionMessageControl.ShowModal("Location and Associated Deleted Successfully!", "RSViewLocations.aspx", true);
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;
            int LocationId = txtLocationId.Text == "" ? 0 : Convert.ToInt32(txtLocationId.Text);
            int CallId = txtCallId.Text == "" ? 0 : Convert.ToInt32(txtCallId.Text);

            string LocationName = txtLocationName.Text;
            string Street = txtStreet.Text;
            string City = txtCity.Text;
            string County = txtCounty.Text;
            string State = txtState.Text;
            string Zip = txtZip.Text;
            string Note = txtLocationNote.Text;


            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationName", SqlDbType.NVarChar, 25, ParameterDirection.Input, LocationName);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Street", SqlDbType.NVarChar, 25, ParameterDirection.Input, Street);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@City", SqlDbType.NVarChar, 25, ParameterDirection.Input, City);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@County", SqlDbType.NVarChar, 15, ParameterDirection.Input, County);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@State", SqlDbType.NVarChar, 15, ParameterDirection.Input, State);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Zip", SqlDbType.NVarChar, 15, ParameterDirection.Input, Zip);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Note", SqlDbType.NVarChar, -1, ParameterDirection.Input, Note);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Active", SqlDbType.Bit, 0, ParameterDirection.Input, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CallId", SqlDbType.Int, 0, ParameterDirection.Input, CallId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveLocation");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);

            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            ucModalActionMessageControl.ShowModal("Location Successfully Saved!", prevurl, true);
        }

        private void LoadLookupLocation()
        {
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            String sqlSELECT =  "SELECT * FROM [rs_tblLocation] WHERE CompanyId=@CompanyID ORDER BY State, City, LocationName";

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = _companyid;
            myCommand.Parameters.Add(param);

            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            Session["DATATABLE"] = ds.Tables[0];
            gvLookupLocation.DataSource = ds;
            gvLookupLocation.DataBind();
            myConnection.Close();
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
           string newSortDirection = String.Empty;

           switch (sortDirection)
           {
              case SortDirection.Ascending:
                 newSortDirection = "ASC";
                 break;

              case SortDirection.Descending:
                 newSortDirection = "DESC";
                 break;
           }
           return newSortDirection;
        }

        protected void gvLookupLocation_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           gvLookupLocation.PageIndex = e.NewPageIndex;
           gvLookupLocation.DataBind();
        }

        protected void gvLookupLocation_Sorting(object sender, GridViewSortEventArgs e)
        {
           DataTable dataTable = Session["DATATABLE"] as DataTable;
           if (dataTable != null)
           {
              DataView dataView = new DataView(dataTable);
              dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

              gvLookupLocation.DataSource = dataView;
              gvLookupLocation.DataBind();
           }
        }

    }
}